<%@ page import="java.sql.*, java.util.*, java.security.MessageDigest, java.security.NoSuchAlgorithmException" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="javax.servlet.http.Cookie" %>
<%
//检查登录
Cookie[] cookies = request.getCookies();
String logonusername = null;
if (cookies != null) {
  for (Cookie cookie : cookies) {
      if ("logonusername".equals(cookie.getName())) {
      	logonusername = cookie.getValue(); // 获取Cookie的值
          break; 
      }
  }
}
request.setAttribute("logonusername", logonusername);

if (logonusername == null) {
    out.println("<script>alert('留言请先登录！');window.location.href='../logon.jsp';</script>");
    return; 
}

    // 获取请求参数
    String msg = request.getParameter("messmsg");
    if(msg==null){
    	out.println("<script>alert('请输入留言');window.location.href='../index.jsp'</script>");
        return; 
    }
    //初始化
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    boolean isValidUser = false;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver"); 
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/message", "message", "message");
        //时间
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
		String time = sdf.format(new java.util.Date());
        //写入
        String insert = "INSERT INTO mess (name, msg, time) VALUES (?, ?, ?)";
        pstmt = conn.prepareStatement(insert);
        pstmt.setString(1, logonusername);
        pstmt.setString(2, msg);
        pstmt.setString(3, time);

        int rows = pstmt.executeUpdate();

        if (rows > 0) {
            out.println("<script>window.location.href='../index.jsp'</script>");
        } else {
            out.println("<script>alert('留言失败，请重试！');window.location.href='../index.jsp'</script>");
        }
        
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        out.println("<script>alert('数据库加载失败！');window.location.href='../index.jsp'</script>");
    }  finally {
        try {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
%>